//
//  FindMeViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/15.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "FindMeViewController.h"
#import "FindMeTableViewCell.h"
#import "CommonService.h"
#import "UIButton+WebCache.h"
//#import "UIImageView+AFNetworking.h"
#import "FindDetailViewController.h"
#import "LoginViewController.h"
#import "FindEntity.h"
#import "UserEntity.h"
#import "FansViewController.h"
#import "PraiseViewController.h"
#import "MoreViewController.h"
#import "DownloadManageViewController.h"
#import "MeProfileViewController.h"
#import "DBManager.h"
#import "MessageViewController.h"
#import "EmptyView.h"
#import "Masonry.h"
#import "OrderViewController.h"
#import "FineMeTableViewSection.h"
#import "UIImageView+WebCache.h"
#import <objc/runtime.h>
typedef enum {
    CYRefreshStatePulling = 1, // 松开就可以进行刷新的状态
    CYRefreshStateNormal = 2, // 普通状态
    CYRefreshStateRefreshing = 3, // 正在刷新中的状态
    CYRefreshStateWillRefreshing = 4
} CYRefreshState;

#define cellheight (104.f/320.f*SCREEN_WIDTH)
#define pageheight (cellheight*7)
#define headviewHeight (208/320.f*SCREEN_WIDTH)
@interface FindMeViewController ()<FindMeDelegate,UIScrollViewDelegate>
{
    CGFloat offsety;
    int page;
}

@property (nonatomic, strong) NSMutableArray *mutableArrayFindMe;
@property (nonatomic, strong) IBOutlet UITableView *tableViewFindMe;
@property (strong, nonatomic) IBOutlet UIView *findmesubview;
@property (weak, nonatomic) IBOutlet UILabel *send_number;
@property (nonatomic, strong) EmptyView *emptyView;
@property (nonatomic, strong) UIButton *btnMyOrderList;
@property (nonatomic, assign) CYRefreshState RefreshState;
@property (nonatomic, strong) FineMeTableViewSection *sectionHeadView;

@end

@implementation FindMeViewController
@synthesize mutableArrayFindMe, tableViewFindMe;
@synthesize userId;
- (instancetype)init
{
    self = [super init];
    if (self) {
        mutableArrayFindMe = [[NSMutableArray alloc] init];
        self.isFromOtherVC = YES;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if (is_IOS_7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _RefreshState = CYRefreshStateNormal;
    _viewNavigation.alpha = 0;
    
    
    self.view.backgroundColor = [UIColor colorWithRed:0.878f green:0.878f blue:0.878f alpha:1.00f];
    tableViewFindMe.backgroundColor = [UIColor colorWithRed:0.878f green:0.878f blue:0.878f alpha:1.00f];
    tableViewFindMe.showsVerticalScrollIndicator = NO;
    tableViewFindMe.contentInset = UIEdgeInsetsMake(headviewHeight, 0, 0, 0);
    
    

    [self addHeadImage];
    
    
    
    
    self.setBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.setBtn.frame = CGRectMake(SCREEN_WIDTH-34, 28, 20, 20);
    [self.view addSubview:self.setBtn];
    [self.setBtn setImage:[UIImage imageNamed:@"findme_setting"] forState:UIControlStateNormal];
    [self.setBtn addTarget:self action:@selector(selectMore) forControlEvents:UIControlEventTouchUpInside];
    [self.naviSet addTarget:self action:@selector(selectMore) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.btnMyOrderList = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnMyOrderList.frame = CGRectMake(SCREEN_WIDTH-74, 28, 20, 20);
    [self.view addSubview:self.btnMyOrderList];
    [self.btnMyOrderList setImage:[UIImage imageNamed:@"我的购买"] forState:UIControlStateNormal];
    [self.btnMyOrderList addTarget:self action:@selector(myOrderListAction) forControlEvents:UIControlEventTouchUpInside];
    [self.naviOrder addTarget:self action:@selector(myOrderListAction) forControlEvents:UIControlEventTouchUpInside];
    [_viewNavigation addObserver:self forKeyPath:@"alpha" options:NSKeyValueObservingOptionNew context:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(judgeIsFromOtherVC) name:Notification_findmeVC_refresh object:nil];

    [self judgeIsFromOtherVC];
    
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if ([tableViewFindMe.subviews containsObject:_emptyView]) {
        return 1;
    }
    return [mutableArrayFindMe count]/3 + ([mutableArrayFindMe count]%3<1?0:1);
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UIView *) tableView:(UITableView *)tableView1 viewForHeaderInSection:(NSInteger)section
{
    return self.sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableViewFindMe.subviews containsObject:_emptyView]) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"clearcell"];
        cell.frame = CGRectMake(0, 0, ScreenWidth, 300);
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell addSubview:_emptyView];
        [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.mas_top).offset(80);
            make.centerX.equalTo(cell.mas_centerX);
            make.width.equalTo(@320);
            make.height.equalTo(@100);
        }];
        return cell;
    }
    static NSString *couponTableViewCellIdentifier=@"FindMeTableViewCell";
    FindMeTableViewCell *cell = (FindMeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FindMeTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        cell.findMeDelegate = self;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row*3 < [mutableArrayFindMe count]) {
        FindEntity *entity = [mutableArrayFindMe objectAtIndex:indexPath.row*3];
            NSString *imageUrl = entity.album_thumb;
//            [cell.imgleft sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"loading"]];
            SDImageCache *imageCache = [SDImageCache sharedImageCache];
            if ([imageCache diskImageExistsWithKey:imageUrl]) {
                [cell.imgleft setImage:[imageCache imageFromDiskCacheForKey:imageUrl]];
            }
            else
            {
                [cell.imgleft sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    if (error == nil && image && tableView && entity) {
                    }
                }];
            }
        cell.btnLeft.tag = indexPath.row*3;
        cell.btnLeft.hidden = NO;
    }
    
    if (indexPath.row*3 + 1 < [mutableArrayFindMe count]) {
        FindEntity *entity = [mutableArrayFindMe objectAtIndex:indexPath.row*3 + 1];
            NSString *imageUrl = entity.album_thumb;
//            [cell.imgmiddle sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"loading"]];
            SDImageCache *imageCache = [SDImageCache sharedImageCache];
            if ([imageCache diskImageExistsWithKey:imageUrl]) {
                [cell.imgmiddle setImage:[imageCache imageFromDiskCacheForKey:imageUrl]];
            }
            else
            {
                [cell.imgmiddle sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    if (error == nil && image && tableView && entity) {
                    }
                }];
            }
        cell.btnMiddle.tag = indexPath.row*3 + 1;
        cell.btnMiddle.hidden = NO;
    }
    
    if (indexPath.row*3 + 2 < [mutableArrayFindMe count]) {
        FindEntity *entity = [mutableArrayFindMe objectAtIndex:indexPath.row*3 + 2];
            NSString *imageUrl = entity.album_thumb;
//            [cell.imgright sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"loading"]];
            SDImageCache *imageCache = [SDImageCache sharedImageCache];
            if ([imageCache diskImageExistsWithKey:imageUrl]) {
                [cell.imgright setImage:[imageCache imageFromDiskCacheForKey:imageUrl]];
            }
            else
            {
                [cell.imgright sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    if (error == nil && image && tableView && entity) {
                        
                    }
                }];
            }
        cell.btnRight.tag = indexPath.row*3 + 2;
        
        cell.btnRight.hidden = NO;
    }
    return cell;
}
- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 104.f/320.f*SCREEN_WIDTH;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 34;
}
#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)findMeButtonAction:(NSInteger) tag {
    FindEntity *entity = [mutableArrayFindMe objectAtIndex:tag];
    
    FindDetailViewController *vc = [[FindDetailViewController alloc] init];
    vc.findEntity = entity;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void) getFineMeData
{
    page = 1;
    [self getFineMeMoreData:page];
    [self getUserInfo];
}

- (void) getUserInfo {
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = nil;
    if (self.spotModel)
    {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 self.spotModel.park_user_id,@"userid",
                 USERID,@"cur_user_id",
                 nil];
    }
    else
    {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 userId, @"userid",
                 USERID,@"cur_user_id",
                 nil];
    }
    [service getNetWorkData:param
                       Path:USER_QUERY_BY_ID
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSDictionary *dic_user = [dic objectForKey:@"row"];
                      
                      UserEntity *userEntity = [[UserEntity alloc] init];
                      userEntity = [userEntity initWithAttributes:dic_user];
                      
                      [self initController:userEntity];
//                      [tableViewFindMe reloadData];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

- (void) initController:(UserEntity *)userEntity {
    
    self.sectionHeadView.labelGZ.text = userEntity.attentionCount;
    self.sectionHeadView.labelFS.text = userEntity.fansCount;
    self.sectionHeadView.labelZan.text = userEntity.goodCount;
    self.sectionHeadView.labelDescription.text = userEntity.signature;
    self.vcTitle.text = userEntity.nickName;
    if (userEntity.userAlbum != nil)
    {
        [self.sectionHeadView.btnHeader sd_setImageWithURL:[NSURL URLWithString:userEntity.userAlbum] forState:UIControlStateNormal];
    }
    else
    {
        [self.sectionHeadView.btnHeader setImage:[UIImage imageNamed:@"头像_03.png"] forState:UIControlStateNormal];
    }
    if ([userEntity.followed isEqualToString:@"1"])
    {
        [self.btnAttention setImage:[UIImage imageNamed:@"hasGZ"] forState:UIControlStateNormal];
    }
    else
    {
        [self.btnAttention setImage:[UIImage imageNamed:@"notGZ"] forState:UIControlStateNormal];
    }
    [self.btnAttention addTarget:self action:@selector(watcheAction:) forControlEvents:UIControlEventTouchUpInside];
    objc_setAssociatedObject(self.btnAttention, @"userEntity", userEntity, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    self.sectionHeadView.labelName.text = userEntity.nickName;

}

- (IBAction)enterFansVC:(id)sender {
    FansViewController *vc = [[FansViewController alloc] init];
    vc.strTitle = @"粉丝";
    vc.strPath = USER_QUERY_FANS;
    vc.findMeVC = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)enterAttendtion:(id)sender {
    FansViewController *vc = [[FansViewController alloc] init];
    vc.strTitle = @"关注";
    vc.strPath = USER_QUERY_ATTENTION;
    vc.findMeVC = self;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)enterPraise:(id)sender {
    PraiseViewController *vc = [[PraiseViewController alloc] init];
    vc.userId = userId;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma scrollviewdelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset   = scrollView.contentOffset.y;
    if (yOffset <= -headviewHeight )
    {
        self.sectionHeadView.imageHeight.constant = -yOffset;
        self.sectionHeadView.frame = CGRectMake(0, yOffset-1, SCREEN_WIDTH , - yOffset);
        if (self.RefreshState == CYRefreshStatePulling)
        {
            UserEntity * entity = [UserEntity sharedInstance];
            if (entity.login == YES ||userId != entity.userId || self.spotModel != nil)
            {
                [self getFineMeData];
            }
        }
        
    }
    else
    {
        DebugLog(@"%f", scrollView.contentOffset.y);
    }
    if (scrollView.contentOffset.y > -headviewHeight) {
        DebugLog(@"%f", scrollView.contentOffset.y);
        _viewNavigation.alpha = 1.0*((scrollView.contentOffset.y + headviewHeight)/(headviewHeight-62));
        [self.view bringSubviewToFront:_viewNavigation];
    } else {

        _viewNavigation.alpha = 0.0;
    }
    
    if (scrollView.contentOffset.y > 182 + (page - 2) * pageheight && _RefreshState == CYRefreshStatePulling)
    {
        [self getFineMeMoreData:page];
    }
    
    if (scrollView.contentOffset.y >= -headviewHeight)
    {
        if (scrollView.contentOffset.y >= -61)
        {
            scrollView.contentInset = UIEdgeInsetsMake(61, 0, 0, 0);
        }
        else
        {
            scrollView.contentInset = UIEdgeInsetsMake(-yOffset, 0, 0, 0);
        }
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    self.RefreshState = CYRefreshStatePulling;
}

- (void)checklogin
{
    UserEntity *entity = [UserEntity sharedInstance];
    
    if (entity.login == YES)
    {
        if ([self.userId isEqualToString:entity.userId])
        {
            MeProfileViewController *mvc = [[MeProfileViewController alloc]init];
            mvc.meVC = self;
            [self.navigationController pushViewController:mvc animated:YES];
        }
    }
    else
    {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)selectMore
{
    MoreViewController *mvc = [[MoreViewController alloc]init];
    [self.navigationController pushViewController:mvc animated:YES];
}

- (void)myOrderListAction
{
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO)
    {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    } else
    {
        OrderViewController *vc = [[OrderViewController alloc] init];
        vc.userId = userEntity.userId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (IBAction)enterMessageVC:(id)sender {
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO)
    {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    
    } else
    {
        MessageViewController *vc = [[MessageViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
       
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"FindMeViewController"];
}
- (IBAction)zujiclick:(id)sender
{
    DownloadManageViewController *mvc = [[DownloadManageViewController alloc]init];
    [self.navigationController pushViewController:mvc animated:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FindMeViewController"];
}

- (void)emptyViewinit
{
    if (self.emptyView == nil) {
        self.emptyView = [[EmptyView alloc]initWithFrame:CGRectMake(0, 0, 320, 100) andImagestr:@"nocontent" andTitle1:@"没有发表内容" andTitle2:@"去发现拍下你喜欢的一切与朋友分享"];
    }
}

- (void)addemptyViewToFront
{
    [self emptyViewinit];
    [self.tableViewFindMe addSubview:self.emptyView];
    [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableViewFindMe.mas_top).offset(80);
        make.centerX.equalTo(self.tableViewFindMe.mas_centerX);
        make.width.equalTo(@320);
        make.height.equalTo(@100);
    }];
}


- (void)getFineMeMoreData:(int)pageNo
{
    CommonService *service = [[CommonService alloc] init];
    NSString *strPage = [NSString stringWithFormat:@"%d",pageNo];
    NSDictionary *param = nil;
    if (self.spotModel)
    {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 strPage, @"page",
                 @"21", @"limit",
                 self.spotModel.park_id,@"park_id",
                 nil];
    }
    else
    {
        param = [NSDictionary dictionaryWithObjectsAndKeys:
                 userId, @"userid",
                 strPage, @"page",
                 @"21", @"limit",
                 nil];
    }
    page ++;
    _RefreshState = CYRefreshStateRefreshing;
    [service getNetWorkData:param
                       Path:USER_TRAVEL
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      NSNumber *code = (NSNumber*)[dic objectForKey:@"code"];
                      _RefreshState = CYRefreshStateNormal;
                      if([code intValue] == 0) {
                          if (pageNo == 1)
                          {
                              [mutableArrayFindMe removeAllObjects];
                          }
                          for (NSDictionary* attributes in array)
                          {
                              FindEntity *entity = [[FindEntity alloc] init];
                              entity = [entity initWithAttributes:attributes];
                              [mutableArrayFindMe addObject:entity];
                          }
                          if ([mutableArrayFindMe count] <= 0 ) {
                              [self addemptyViewToFront];
                          }
                          else
                          {
                              [self.emptyView removeFromSuperview];
                          }
                          dispatch_async(dispatch_get_main_queue(), ^{
                              self.send_number.text = [NSString stringWithFormat:@"%@个发表",[dic objectForKey:@"total"]];
                              [tableViewFindMe reloadData];
                          });

                      }
                      else
                      {
                          [self addemptyViewToFront];
                          [tableViewFindMe reloadData];
                      }
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                      page --;
                  }];
}

- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary *)change context:(nullable void *)context
{
//    NSLog(@"_viewNavigation.alpha = %f",_viewNavigation.alpha);
    if ([keyPath isEqualToString:@"alpha"])
    {
        if (_isFromOtherVC)
        {
            if (_viewNavigation.alpha < 0.15)
            {
                _backBtn.hidden = NO;
            }
            else
            {
                _backBtn.hidden = YES;
            }
        }
    }
}

- (void)dealloc
{
    [_viewNavigation removeObserver:self forKeyPath:@"alpha"];
}


- (void)judgeIsFromOtherVC
{
    UserEntity *entity = [UserEntity sharedInstance];
    if (userId.length <= 0)
    {
        userId = entity.userId;
    }
    //findmevc 如果不是自己的首页 则隐藏足迹
    if (self.isFromOtherVC) {
        self.backBtn.hidden                     = NO;
        self.setBtn.hidden                      = YES;
        self.btnMyOrderList.hidden              = YES;
        self.sectionHeadView.zujiWidth.constant = 0;
        self.sectionHeadView.footLabel.hidden   = YES;
        self.sectionHeadView.foot_number.hidden = YES;
        self.naviOrder.hidden                   = YES;
        self.naviSet.hidden                     = YES;
        self.naviBack.hidden                    = NO;
    }
    else
    {
        self.backBtn.hidden                     = YES;
        self.setBtn.hidden                      = NO;
        self.sectionHeadView.zujiWidth.constant = ScreenWidth/4.0;
        self.btnAttention.hidden       = YES;
    }
    self.sectionHeadView.foot_number.text = [NSString stringWithFormat:@"%zi",[[DBManager selectAllDownloadPark] count]];
    if (entity.login == YES ||userId != entity.userId || self.spotModel != nil)
    {
        [self getFineMeData];
    }
    else
    {
        [self addemptyViewToFront];
        [mutableArrayFindMe removeAllObjects];
        [self.tableViewFindMe reloadData];
        UserEntity *userEntity = [[UserEntity alloc] init];
        userEntity.attentionCount = @"0";
        userEntity.fansCount = @"0";
        userEntity.goodCount = @"0";
        userEntity.signature = @"";
        userEntity.nickName = @"点击登录";
        [self initController:userEntity];
    }

}

- (void)addHeadImage
{
    FineMeTableViewSection *head= (FineMeTableViewSection *)[[[NSBundle  mainBundle]  loadNibNamed:@"FineMeTableViewSection" owner:self options:nil]  lastObject];
    head.frame = CGRectMake(0, -headviewHeight, ScreenWidth, headviewHeight);
    self.sectionHeadView = head;
    self.sectionHeadView.imageHeight.constant = headviewHeight;
    [tableViewFindMe addSubview:head];
    [self.view addSubview:self.findmesubview];
    [self.sectionHeadView.btnHeader addTarget:self action:@selector(checklogin) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionHeadView.messageButton addTarget:self action:@selector(enterMessageVC:) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionHeadView.btnGZ addTarget:self action:@selector(enterAttendtion:) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionHeadView.btnFS addTarget:self action:@selector(enterFansVC:) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionHeadView.btnZG addTarget:self action:@selector(enterPraise:) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionHeadView.btnZJ addTarget:self action:@selector(zujiclick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void) watcheAction:(UIButton*)button {
    UserEntity *entity = [UserEntity sharedInstance];
    
    if (entity.login == NO)
    {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
   UserEntity* userEntity = objc_getAssociatedObject(button, @"userEntity");
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           userEntity.userId,@"attention_id",
                           USERID,@"userid",
                           nil];
    if ([userEntity.followed isEqualToString:@"0"])
    {
        [self showLoadingView:YES];
        [service getNetWorkData:param
                           Path:USER_ATTENTION
                      Successed:^(id entity) {
                          NSDictionary *dic = (NSDictionary *)entity;
                          NSNumber *code = [dic objectForKey:@"code"];
                          [self showLoadingView:NO];
                          if ([code intValue] == 0) {
                              [self getUserInfo];
                              [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findview_refresh object:nil];
                              ALERT_ERR_MSG(@"关注成功");
                          } else {
                              ALERT_ERR_MSG(@"关注失败");
                          }
                      } Failed:^(NSInteger errorCode, NSString *message) {
                      }];
    }
    if ([userEntity.followed isEqualToString:@"1"])
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确认对TA取消关注吗？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alert show];
        objc_setAssociatedObject(alert, @"userEntity", userEntity, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UserEntity* userEntity = objc_getAssociatedObject(alertView, @"userEntity");
    if (buttonIndex == 1) {
        CommonService *service = [[CommonService alloc] init];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               userEntity.userId,@"attention_id",
                               USERID,@"userid",
                               nil];
        [service getNetWorkData:param
                           Path:USER_ATTENTION
                      Successed:^(id entity) {
                          NSDictionary *dic = (NSDictionary *)entity;
                          NSNumber *code = [dic objectForKey:@"code"];
                          [self showLoadingView:NO];
                          if ([code intValue] == 0) {
                              [self getUserInfo];
                              [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findview_refresh object:nil];
                              ALERT_ERR_MSG(@"取消关注成功");
                          } else {
                              ALERT_ERR_MSG(@"取消关注失败");
                          }
                      } Failed:^(NSInteger errorCode, NSString *message) {
                      }];

    }
}

@end